import os
import random
import subprocess
from src.utils.logger import log_info

class VideoNormalizer:
    """处理视频标准化、转码等操作"""
    
    def __init__(self, startupinfo=None, logger=None):
        self.startupinfo = startupinfo
        self.logger = logger
    
    def normalize_video(self, video_path, output_path=None, target_width=None, target_height=None):
        """标准化视频为统一格式和分辨率"""
        if output_path is None:
            from tempfile import mkdtemp
            temp_dir = mkdtemp(prefix="video_norm_")
            os.makedirs(temp_dir, exist_ok=True)
            output_path = os.path.join(temp_dir, f"normalized_{random.randint(1000, 9999)}.mp4")
        
        cmd = [
            "ffmpeg",
            "-i", video_path,
            "-vf", f"fps=30,scale={target_width}:{target_height}:force_original_aspect_ratio=decrease,pad={target_width}:{target_height}:(ow-iw)/2:(oh-ih)/2",
            "-c:v", "libx264",
            "-preset", "veryfast",
            "-crf", "23",
            "-c:a", "aac",
            "-b:a", "192k",
            "-y",
            output_path
        ]
        log_info(f"[INFO] 标准化视频 {os.path.basename(video_path)} 到 {target_width}x{target_height}")
        subprocess.run(cmd, check=True, startupinfo=self.startupinfo)
        return output_path
    
    def convert_video_to_ts(self, video_path, target_width=None, target_height=None, temp_file_path=None):
        """将单个视频转换为TS格式"""
        if not temp_file_path:
            from tempfile import mkstemp
            fd, temp_file_path = mkstemp(prefix="ts_", suffix=".ts")
            os.close(fd)
        
        cmd = [
            "ffmpeg",
            "-i", video_path,
            "-vf", f"fps=30,scale={target_width}:{target_height}:force_original_aspect_ratio=decrease,pad={target_width}:{target_height}:(ow-iw)/2:(oh-ih)/2",
            "-c:v", "libx264",
            "-preset", "veryfast",
            "-crf", "23",
            "-c:a", "aac",
            "-b:a", "192k",
            "-f", "mpegts",
            "-y",
            temp_file_path
        ]
        log_info(f"[INFO] 转码为 TS: {os.path.basename(video_path)} -> {target_width}x{target_height}")
        subprocess.run(cmd, check=True, startupinfo=self.startupinfo)
        return temp_file_path
    
    def merge_ts_files(self, ts_files, output_path):
        """合并多个TS文件"""
        concat_str = "|".join(ts_files)
        merge_cmd = [
            "ffmpeg",
            "-i", f"concat:{concat_str}",
            "-c", "copy",
            "-bsf:a", "aac_adtstoasc",
            "-y",
            output_path
        ]
        log_info(f"[INFO] 开始合并 TS: {' '.join(merge_cmd)}")
        subprocess.run(merge_cmd, check=True, startupinfo=self.startupinfo)
        log_info(f"[INFO] 合并完成: {output_path}")
        return output_path